<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<% String path=request.getContextPath(); String basePath=request.getScheme()+ "://" + request.getServerName() + ":" + request.getServerPort() + path+ "/"; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>投入产出分析报表</title>
<base href="<%=basePath%>">

<%@ include file="/WEB-INF/jsp/common/common.jsp" %>

<link rel="stylesheet" href="css/jquery.datetimepicker.css" type="text/css" />
<script src="js/jquery.validate.js" type="text/javascript" ></script>
<script src="js/jquery.divbox.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.datetimepicker.js"></script>

<style type="text/css">
    /* 清除浮动 */
    .clearfix:after {
      visibility: hidden;
      display: block;
      font-size: 0;
      content: " ";
      clear: both;
      height: 0;
    }
    .hide {
        display: none;
    }
    /* -------------------------------- 查询条件 start -------------------------- */
    .filter_condition select,
    .filter_condition input[type="text"] {
        width: 100px;
        height: 30px;
        line-height: 28px;
        padding-left: 8px;
    }
    .filter_condition span {
        padding-right: 15px;
    }
    .filter_condition .tab_btn {
        width: 10px;
        height: 10px;
        margin: 0 10px;
    }

    /* -------------------------------- 查询条件 end -------------------------- */
    .policyAmountTable .f2.even {
        background: #ECF5FC;
    }
    .policyAmountTable .f2.selected {
        background: #ccc;
    }
    .policyAmountTable .border_bottom{
        border-bottom: 1px solid #bbcddb;
    }
    .policyAmountTable .see_span {
        color: blue;
        cursor: pointer
    }
    /*------------------------------- 20190903 lfd added 修改样式 start -------------------------------------*/
    /* --------- common start ----------- */
    /* 清除浮动 */
    .clear {
        clear: both;
    }

    .w_50 {
        width: 50%;
        display: inline-block;
    }
    /* --------- common end ----------- */
    .search_container, .query_results {
        padding: 10px 20px;
        -moz-border-radius: 20px;
             border-radius: 20px;
        background: #fff;
        margin: 10px 20px 10px 10px;
        -moz-box-shadow: 0px 0px 15px #eee; /* 老的 Firefox */
        -webkit-box-shadow: 0px 0px 15px #eee;
                box-shadow: 0px 0px 15px #eee;
        line-height: 30px;
    }
    .search_container .search_tit, .query_results .query_tit{
        color: #f38963;
        font-size: 16px;
        font-weight: 700;
        padding-bottom: 20px;
    }
    .search_container .search_item {
        width: 30%;
        margin: 5px 1.5%;
        float: left;
    }
    .search_container .search_item span {
        width: 90px;
        display: inline-block;
    }

    .search_container .search_item .hide {
        display: none;
    }
    .search_container .search_item input,
    .search_container .search_item select {
        width: 120px;
        height: 30px;
        line-height: 30px;
        -moz-border-radius: 3px;
             border-radius: 3px;
    }

    .search_container .search_item .readonly{
        background: #eee;
    }

    .search_container .search_item .input_button_s {
        width: 55px;
        line-height: 30px;
        text-align: center;
        -moz-border-radius: 4px;
             border-radius: 4px;
        border-style: none;
        /* border: none; */
        background: #3cabd3;
        color: #fff;
    }
    /* ------ 单选框、多选框样式 start ----- */
    .search_container .search_item label.check_span {
        position: relative;
        display: inline-block;
    }
    .search_container .search_item input[type="checkbox"],
    .search_container .search_item input[type="radio"]{
        width: 15px;
        height: 15px;
        opacity: 0;
        margin-left: 10px;
    }
    .search_container .search_item .check_span label {
        position: absolute;
        left: 0px;
        top: 6px;
        width: 15px;
        height: 15px;
        border: 1px solid #dcdcdc;
    }
    label.checkbox {
        -moz-border-radius: 2px;
             border-radius: 2px;
    }
    label.radio {
        -moz-border-radius: 50%;
             border-radius: 50%;
    }
    /*设置选中的input的样式*/
    /* + 是兄弟选择器,获取选中后的label元素*/
    .search_container .search_item input:checked+label {
        background-color: #3cabd3;
        border: 1px solid #3cabd3;
    }
    .search_container .search_item input:checked[type="checkbox"]+label::after {
        position: absolute;
        content: "";
        width: 5px;
        height: 7px;
        top: 2px;
        left: 4px;
        border: 2px solid #fff;
        border-top: none;
        border-left: none;
        -webkit-transform: rotate(45deg);
           -moz-transform: rotate(45deg);
                transform: rotate(45deg)
    }
    .search_container .search_item input:checked[type="radio"]+label::after {
        position: absolute;
        content: "";
        width: 5px;
        height: 5px;
        -moz-border-radius: 3px;
             border-radius: 3px;
        background: #fff;
        top: 5px;
        left: 5px;
    }
    /* ------ 单选框、多选框样式 end ----- */
    .search_container .search_btns {
        padding: 20px;
        text-align: center;
    }
    .search_container .search_btn,
    .search_div .table_div .search_btn {
        border: 1px solid #3cabd3;
        background: #fff;
        -moz-border-radius: 15px;
             border-radius: 15px;
        height: 30px;
        line-height: 30px;
        padding: 0 15px;
        color: #3cabd3;
        outline: none;
    }
    .search_container .search_btn.reset,
    .search_div .table_div .search_btn.reset {
        border: 1px solid #b5b5b5;
        color: #7f7f7f;
    }
    /* 提示信息样式 */
    /* .query_results.tip_box {
        display: none;
    }
    .query_results .close_tips {
        float: right;
        padding-right: 15px;
        font-size: 15px;
        color: #3cabd3;
        cursor: pointer;
    }
    .query_results .tips {
        color: #3cabd3;
    } */

    .query_results .tips {
        color: #3cabd3;
        float: right;
        font-size: 12px;
        font-weight: 400;
    }

    /* 表格样式修改 start */
    .query_results .content_table_1 {
        border-collapse: collapse;
    }

    .query_results .content_table_1 .f1 {
        background: #d8eef6;
        height: 30px;
        line-height: 30px;
    }
    .query_results .content_table_1 th,
    .query_results .content_table_1 td {
        border: 1px solid #d2d2d2;
    }
    .query_results .content_table_1 .f1 th {
        background: #d8eef6;
    }
    .next_tr {
        background: #eee;
    }
    .page {
        background: transparent;
        margin-top: 15px;
    }
    .policyAmountTable .see_span {
        color: #f5996c;
        border: 1px solid #f5996c;
        -moz-border-radius: 3px;
             border-radius: 3px;
        line-height: 22px;
        width: 50px;
        display: inline-block;
        margin: 3px 5px;
    }
    /* 表格样式修改 end */
    /* 弹窗样式 start */
    .search_div {
        -moz-border-radius: 20px;
             border-radius: 20px;
    }
    .search_div .table_div {
        padding: 30px 20px 10px;
    }
    .search_div .table_div .table_tit {
        font-weight: 700;
        font-size: 20px;
        text-align: center;
        line-height: 48px;
        height: 48px;
    }
    .search_div .table_div .search_row {
        height: 40px;
        line-height: 40px;
    }
    .search_div .table_div .search_item  {
        float: left;
    }
    .search_div .table_div .queryResults {
        padding-top: 10px;
    }
    .search_div  .popup_button {
        margin: 10px 3px 20px;
        background: -webkit-gradient(linear, left top, right top, from(#319dcf), to(#085192));
        background: -webkit-linear-gradient(left, #319dcf, #085192);
        background: -moz-linear-gradient(left, #319dcf, #085192);
        background: linear-gradient(to right, #319dcf, #085192); /* 标准的语法 */
        width: 80px;
        height: 30px;
        line-height: 30px;
        -moz-border-radius: 5px;
             border-radius: 5px;
        color: #fff;
        border-style: none;
        border: 1px solid #319dcf;
    }
    .search_div  .popup_button.cancel {
        color: #a0a0a0;
        background: #fff;
        border: 1px solid #a0a0a0;
    }
    /* 弹窗样式 end */
    /*------------------------------- 20190903 lfd added 修改样式 end -------------------------------------*/
    /* 20191115 lfd added 查询机构数据样式 */
    .subtable_box {
        padding: 20px 10px;
        background: #fffaf8;
    }
    .query_results .subtable_box .content_table_1 .f1{
        background: #fbe7dd;
    }
    .query_results .subtable_box .content_table_1 .f1 th {
        background: transparent;
    }
     .query_results .content_table_1  .noborder {
        border: none;
    }
    /* -------------- 分页样式 start lfd changed 20191119 --------------- */
    .page_checked {
        color: f5996c;
    }
    .page_a .page_a_click {
        color: f5996c;
        background: transparent;
    }
    /* -------------- 分页样式 end lfd changed 20191119 --------------- */
    /* -------查询合伙伙伴代码弹窗添加滚动------ */
    .queryResults .templetTableBox{
        height: 161px;
        overflow-y: auto;
        overflow-x: hidden;
        width: 100%;
    }
</style>
<body>
    <div class="current">
        <table class="current_table_1">
            <tbody>
                <tr class="f2">
                    <td><img src="./images/current_1.jpg"></td>
                    <td class="current_table_1_td"><img src="images/current_1.png">
	                    当前位置：统计分析<span style="padding: 0 4px; font-weight: bold; line-height: 28px;">&gt;</span>投入产出分析报表
                    </td>
                    <td><img src="./images/current_3.jpg"></td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="search_container">
        <div class="search_tit">查询条件</div>
        <div class="search_box">
            <div class="search_item">
                <span>产品线:</span>
                <!-- 1 人险 2 财险 3 新意健险 4 车险 5 信用保证险  99 责任险 -->
                <select name="product_line" id="product_line">
                    <option value="">--请选择--</option>
                    <option value="1">人险</option>
                    <option value="2">财险</option>
                    <option value="4">车险</option>
                    <option value="5">信保</option>
                    <option value="3">意健险</option>
                    <option value="99">责任险</option>
                </select>
            </div>
            <div class="search_item">
                <span>合作伙伴名称：</span>
                <!-- <select name="ptn_name" id="ptn_name"></select> -->
                <input name="ptn_name" id="ptn_name" readonly="readonly" class="input_text readonly"/><span class="hide" id="ptn_code"></span>
                <input type="button" class="input_button_s" value="请选择" onClick="setPartnerParam(1)" />
            </div>
            <div class="search_item">
                <span>机构：</span>
                <select name="dpt_name" id="dpt_name"></select>
            </div>
            <div class="clear"></div>
        </div>
        <div class="search_box">
            <div class="search_item">
                <span>日期：</span>
                <input name="currentTime" id="currentTime" readonly="readonly" class="input_text readonly"/>
            </div>
            <div class="search_item">
                <span>查询内容：</span>
                <label class="check_span">
	                <input type="checkbox" class="tab_btn" id="ispolicy" checked="checked"/><label for="ispolicy" class="checkbox"></label>单量
                </label>
                <label class="check_span">
	                <input type="checkbox" class="tab_btn" id="ispremium" checked="checked"/><label for="ispremium" class="checkbox"></label>保费
                </label>
            </div>
            <div class="search_item">
                <span>数字格式：</span>
                <label  class="check_span">
                    <input type="radio" class="tab_btn" name="number_format" checked id="numberFormat0" value="0"/><label for="numberFormat0" class="radio"></label>个
                </label>
                <label class="check_span">
                    <input type="radio" class="tab_btn" name="number_format" id="numberFormat1" value="1"/><label for="numberFormat1" class="radio"></label>万
                </label>
            </div>
            <div class="clear"></div>
        </div>
        <div class="search_btns">
            <input type="button" class="search_btn" value="查询" onClick="setAmountParam(1)" />
            <input type="button" class="search_btn reset" value="重置" onClick="reset()" />
            <input type="button" class="search_btn" value="excel导出" onClick="downloadLifePolicyFile()" />
        </div>
    </div>

    <!-- <div class="query_results tip_box" id="tip_box">
        <div class="query_tit">提示信息<span class="close_tips" onclick="closeCurrentDIV('tip_box')">关闭</span></div>
        <div class="tips"></div>
    </div> -->


    <div class="query_results">
        <div class="query_tit">查询结果  <span class="tips"></span></div>
        <!-- 单量、保费汇总 start -->
         <div>
             <table id="policyAmountTable" class="content_table_1 policyAmountTable">
                 <thead>
                     <!-- <tr class="f1">
                         <th style="width:5%;">选择</th>
                         <th style="width:8%;">合作伙伴名称</th>
                         <th style="width:6%;">机构</th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:6%;"></th>
                         <th style="width:8%;">单量汇总</th>
                     </tr> -->
                 </thead>
                 <tbody>
                 </tbody>
             </table>
         </div>
         <div id="txproductpageDIV" class="page"></div>
         <!-- 单量、保费汇总 end -->
    </div>


    <!-- 查询合作伙伴 弹窗 start -->
    <div id="searchPartnerDiv"  class="search_div" style="display:none;width:60%;">
        <!-- <div class="table_title_div">
            <table class="table_title" style='width:100%;height:20px;'>
                <tr>
                <td width="10%"></td>
                <td width="80%"></td>
                <td width="10%" align="right"><img src="./images/closedown.gif" alt="关闭"  onclick="closeCurrentDIV('searchPartnerDiv')"/></td>
                </tr>
            </table>
        </div> -->
        <div  class="table_div">
            <div class="table_tit">查询合作伙伴名称</div>
            <div class="table_box">
                <div class="search_div">
                    <div class="search_row">
                        <span class="search_item w_50">合作伙伴名称：
                            <input id="partner_name" type="text" class="input_text">
                        </span>
                        <span class="search_item w_50">合作伙伴代码：
                            <input id="partner_code" type="text" class="input_text">
                        </span>
                        <div class="clear"></div>
                    </div>
                    <div class="search_row">
                        <input type="button" class="search_btn" value="查询" onclick="setPartnerParam(1)">
                        <input type="button" class="search_btn reset" value="重置" onclick="tempReset()">
                    </div>
                </div>
            </div>
            <div class="queryResults">
                <div class="templetTableBox">
	                <table id="templetTable" class="content_table_1">
	                    <thead>
	                        <tr class="f1">
	                            <th style="width: 5%">选择</th>
	                            <th style="width: 20%">合作伙伴代码</th>
	                            <th style="width: 65%">合作伙伴名称</th>
	                        </tr>
	                    </thead>
	                    <tbody>
	                    </tbody>
	                </table>
                </div>
                <div id="templetpageDIV" class="page"></div>
            </div>
        </div>
        <div align="center" >
            <input class="popup_button" type="button" value="确定" onclick="setPartner(0)">
            <input class="popup_button cancel" type="button" value="取消" onclick="closePartnerDiv()">
        </div>
    </div>
    <!-- 查询合作伙伴 弹窗 end -->




    <script>
    	/* ie不支持 */
    	var BrowserDetect = {
    	      dataBrowser: [{
    	        string: navigator.userAgent,
    	        subString: 'Chrome',
    	        identity: 'Chrome'
    	      },
    	      {
    	        string: navigator.vendor,
    	        subString: 'Apple',
    	        identity: 'Safari',
    	        versionSearch: 'Version'
    	      },
    	      {
    	        prop: window.opera,
    	        identity: 'Opera',
    	        versionSearch: 'Version'
    	      },
    	      {
    	        string: navigator.userAgent,
    	        subString: 'Firefox',
    	        identity: 'Firefox'
    	      },
    	      {
    	        string: navigator.userAgent,
    	        subString: 'MSIE',
    	        identity: 'Explorer',
    	        versionSearch: 'MSIE'
    	      },
    	      {
    	        string: navigator.userAgent,
    	        subString: 'Gecko',
    	        identity: 'Mozilla',
    	        versionSearch: 'rv'
    	      },
    	      {
    	        // for older Netscapes (4-)
    	        string: navigator.userAgent,
    	        subString: 'Mozilla',
    	        identity: 'Netscape',
    	        versionSearch: 'Mozilla'
    	      }],
    	      init: function () {
    	        this.browser = this.searchString(this.dataBrowser) || 'An unknown browser'
    	        this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || 'an unknown version'
    	      },
    	      searchString: function (data) {
    	        for (var i = 0; i < data.length; i++) {
    	          var dataString = data[i].string
    	          var dataProp = data[i].prop
    	          this.versionSearchString = data[i].versionSearch || data[i].identity
    	          if (dataString) {
    	            if (dataString.indexOf(data[i].subString) !== -1) {
    	              return data[i].identity
    	            }
    	          } else if (dataProp) {
    	            return data[i].identity
    	          }
    	        }
    	      },
    	      searchVersion: function (dataString) {
    	        var index = dataString.indexOf(this.versionSearchString)
    	        if (index === -1) {
    	          return
    	        }
    	        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1))
    	      }
    	    }
    	    BrowserDetect.init()
    	    if (BrowserDetect.version <= 8 && BrowserDetect.browser === 'Explorer') {
    	      window.location.href = './report/download'
    	    }
    
    
    
        // lfd 20191115 全局 单位
        var unit = ''

        /**
         * 对Date的扩展，将 Date 转化为指定格式的String
         * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
         * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
         * @param     {string}       num       格式
         * @example   (new Date()).Format('yyyy-MM-dd hh:mm:ss.S') ==> 2006-07-02 08:09:04.423
         *            (new Date()).Format('yyyy-M-d h:m:s.S')      ==> 2006-7-2 8:9:4.18
         */
        Date.prototype.Format = function (fmt) {
          var o = {
            'M+': this.getMonth() + 1, //月份
            'd+': this.getDate(), //日
            'h+': this.getHours(), //小时
            'm+': this.getMinutes(), //分
            's+': this.getSeconds(), //秒
            'q+': Math.floor((this.getMonth() + 3) / 3), //季度
            'S': this.getMilliseconds() //毫秒
          }
          if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
          }
          for (var k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
              fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
            }
          }
          return fmt
        }

         /**
          * 将长数字格式化
          * @DateTime  2018-01-18
          * @version   1.0
          * @param     {num}       num       将要格式化的数字
          * @param     {num}       precision 小数保留位数
          * @param     {string}    separator 分隔符
          * @return    {string}              格式化后的数字 例如 "1,000" 或者 "56 000.00"
          */
         function formatNumber(num, precision, separator, level) {
           var parts
           // 判断是否为数字
           if (!isNaN(parseFloat(num)) && isFinite(num)) {
             // 把类似 .5, 5. 之类的数据转化成0.5, 5, 为数据精度处理做准备
             // 为什么不在判断中直接写 if (!isNaN(num = parseFloat(num)) && isFinite(num))
             // parseFloat有一个奇怪的精度问题, 比如 parseFloat(12312312.1234567119) 的值变成了 12312312.123456713
             num = Number(num)

             // 处理量级
             if(level) {
                 num = num/level
              }

             // 处理小数点位数
             num = (typeof precision !== 'undefined' ? num.toFixed(precision) : num).toString()
             // 分离数字的小数部分和整数部分
             parts = num.split('.')
             // 整数部分加[separator]分隔, 借用一个著名的正则表达式
             // parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + (separator || ','))
             parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + (separator || ''))
             return parts.join('.')
           }
           return NaN;
         }

        /* 初始化 */
        $(function () {
            /* 选择日期 */
            $('#currentTime').datetimepicker({
                lang: 'ch',
                validateOnBlur: false,
                timepicker: false,
                format: 'Y-m-d',
                maxDate: '0',
                onChangeDateTime: changeTermDate, // 回调函数
                scrollMonth: false,
                scrollTime: false
            });

            /* 获取单量 */
            setAmountParam(1)

            /* 获取合作伙伴名称 */
            // queryPtnName()
            /* 获取机构 */
            queryAllDept()

        })

        //统一 关闭  窗口
		function closeCurrentDIV(obj){
		    $("#"+obj).CloseDiv();
		}

        // 取近12个月日期
        function last_year_month() {
            var currentTime = $('#currentTime').val()
            var d = currentTime?new Date(currentTime.replace(/-/g, '/')) :new Date();
            var result = [];
            for(var i = 0; i < 12; i++) {
                var m = d.getMonth() + 1;
                m = m < 10 ? "0" + m : m;
                //在这里可以自定义输出的日期格式
                result.unshift(d.getFullYear() + "-" + m );
                d.setMonth(d.getMonth() - 1);
            }
            return result;
        }
        /* 设置表格头 */
        function getHead () {
            var month_str = ''
            $.each(last_year_month(), function(index, el) {
                month_str += '<th style="width:5%;">' + el + '</th>'
            });

            return  month_str
        }

        /* 选择判断今天不能选 */
        function changeTermDate(){
            var countDate = new Date($("#currentTime").val().replace(/-/g, '/'));
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth()
            var day = date.getDate()
            var nowDate = new Date(year, month, day)
            if(countDate >= nowDate){
                $("#currentTime").val('')
                alert('请选择今天之前的日期。')
            }
        }

        /* 重置按钮 */
        function reset() {
            $('#product_line').val('')
            $('#ptn_name').val('')
            $('#ptn_code').val('')
            $('#dpt_name').val('')
            $('#currentTime').val('')
            $('.tab_btn').attr("checked","checked")
            $('#numberFormat1').attr("checked", false)
            $('#numberFormat0').attr("checked", true)
        }

        /* 查询合作伙伴 */
        /* function queryPtnName() {
            $.ajax({
                url : "dataManage/queryPtnName",
                type : 'POST',
                async : true,
                dataType:'json',
                success : function(data) {
                    var str = '<option value="">--请选择--</option>'
                    $.each(data, function (i, v) {
                        str += '<option value="' + v.PARTNER_CODE + '">' + v.PARTNER_CODE + '--' + v.CHANNEL_NAME +  '</option>'
                    })
                    $('#ptn_name').html(str)
                }
            })
        } */

        /* 查询机构 */
        function queryAllDept() {
            $.ajax({
                url : "dataManage/queryAllDept",
                type : 'POST',
                async : true,
                dataType:'json',
                success : function(data) {
                    var str = '<option value="">--请选择--</option>'
                    $.each(data, function (i, v) {
                        str += '<option value="' + v.DEPT_CODE + '">' + v.DEPT_CODE + '--' + v.DEPT_ABR +  '</option>'
                    })
                    $('#dpt_name').html(str)
                }
            })
        }

        /* 配置参数 */
        function setAmountParam(displayPage, size) {
        	if (!size) {
        		size = 10
        	}
            var jsonData = {
                current: displayPage,
                size:size,
                "countDate": $('#currentTime').val()?$('#currentTime').val():(new Date()).Format('yyyy-MM-dd'),
                "depCode": $('#dpt_name').val()?$('#dpt_name').val():"",
                // 机构名称
                "dptName": $('#dpt_name').val()?$("#dpt_name").find("option:selected").text():"",
                "depAbr": $('#dpt_name').text()?$('#dpt_name').text().split('-')[1]:"",
                // lfd added 20190910 选框改为弹窗选择
                // "partnerCode": $('#ptn_name').val()?$('#ptn_name').val():"",
                "partnerCode": $('#ptn_code').val()?$('#ptn_code').val():"",
                "policyType": $('#product_line').val()=="99"?"2":$('#product_line').val(),
                "ispolicy": document.getElementById('ispolicy').checked,
                "ispremium": document.getElementById('ispremium').checked,
                "isLiability": $('#product_line').val()=="99"?true:false
            }
            queryAmount(jsonData)
        }
        /* 获取数据 */
        function queryAmount (jsonData) {
            if (!jsonData || (!jsonData.ispolicy && !jsonData.ispremium)) {
                $.message("error", "请选择至少一项进行查询！");
                return false
            }
            $.openLoading();
            $.ajax({
                url : "dataManage/queryAmount",
                type : 'POST',
                async : true,
                dataType:'json',
                data: jsonData,
                success : function(page) {
                    $.closeLoading();

                    if (!page || (page.data.length === 0)) {
                        $.message("error", "抱歉，该项没有数据！");
                    }
                    var data = page.data

                    // 查询单位变化 全局 lfd added 20191114
                    if ($('#numberFormat1').attr('checked')) {
                        unit = '万'
                    } else {
                        unit = ''
                    }

                    if (unit === '万') {
                    	// 整理数据
                        $.map(data, function (v, i) {
                            for(prop in v) {
                                if (prop != 'DEPT_ABR' && prop != 'DEPT_CODE' && prop != 'PARTNER_CODE'&& prop != 'CHANNEL_NAME'&& prop != 'CHANNEL_COST') {
                                    v[prop] = formatNumber(v[prop], 2, '', 10000)
                                }
                            }
                            return v
                        })
                    }

                    /* 取近十二个月作为表格头 */
                    // var policy_thead_str = '<tr class="f1"><th style="width:3%;">选择</th><th style="width:3%;">序号</th><th style="width:8%;">合作伙伴名称</th><th style="width:5%;">机构</th>'
                    // var policy_thead_str = '<tr class="f1"><th style="width:3%;">序号</th><th style="width:8%;">合作伙伴名称</th><th style="width:5%;">机构</th>'
                    var policy_thead_str = '<tr class="f1"><th style="width:3%;">序号</th><th style="width:6%;">合作伙伴名称</th>'

                    // lfd added 如果有机构才展示机构 否则不展示 20191115
                    if (jsonData.depCode) {
                    	policy_thead_str += '<th style="width:5%;">机构</th>'
                   	}

                    policy_thead_str += getHead()
                    // 添加今年总量 lfd added 20191121
                    policy_thead_str += '<th style="width:4%;">近12个月</th><th style="width:4%;">今年总量</th><th style="width:4%;">汇总</th>'

                    // 查询机构不展示投产比
                    if(!jsonData.dptName) {
                    	policy_thead_str += '<th style="width:4%;">操作</th></tr>'
                    }

                    $('#policyAmountTable').find('thead').html(policy_thead_str)


                    var str = ''

                    $.each(data, function (i, v){
                    	// lfd changed 如果有机构才展示机构 否则不展示 20191115
                        // str += '<tr class="f2"><td><input class="f2_radio" name="f2_radio" type="radio"></td><td>' + (i+1) + '</td><td>' + v.PARTNER_CODE +'-' + v.CHANNEL_NAME + '</td><td>' + jsonData.dptName + '</td><td>'
                        str += '<tr class="f2"><td>' + (i+1) + '</td><td>' + v.PARTNER_CODE +'-' + v.CHANNEL_NAME + '</td>'
                        if (jsonData.depCode) {
                        	str += '<td>' + jsonData.dptName + '</td>'
                        }
                        str += '<td>'

                        if (jsonData.ispolicy && jsonData.ispremium){
                            for (k = 11; k>=0; k--) {
                                str += '<div class="border_bottom">' + v['COUNT' + k] + '</div><div>' + v['PREMIUM' + k] + '</div></td><td>'
                            }
                            str += '<div class="border_bottom">' + v.POL_NUM + '</div><div>' + v.PREMIUM + '</div></td>'
                            str += '<td><div class="border_bottom">' + v.ANNUAL_TOTAL_POL + '</div><div>' + v.ANNUAL_TOTAL_PREMIUM + '</div></td>'
                            str += '<td><div class="border_bottom">' + v.ALLCOUNT + '</div><div>' + v.ALLPREMIUM + '</div></td>'
                        } else if (jsonData.ispolicy) {
                            for (k = 11; k>=0; k--) {
                                str += v['COUNT' + k] + '</div></td><td>'
                            }
                            str += v.POL_NUM + '</td><td>'
                            str += v.ANNUAL_TOTAL_POL + '</td><td>'
                            str += v.ALLCOUNT + '</td>'
                        } else if (jsonData.ispremium){
                            for (k = 11; k>=0; k--) {
                                str += v['PREMIUM' + k] + '</div></td><td>'
                            }
                            str += v.PREMIUM + '</td><td>'
                            str += v.ANNUAL_TOTAL_PREMIUM + '</td><td>'
                            str += v.ALLPREMIUM + '</td>'
                        } else {
                            str += ''
                        }


                        // 查询机构不展示投产比
                        if(!jsonData.dptName) {
                            // 投产比 ALLPREMIUM CHANNEL_COST
                        	/* var all
                            if ($('#numberFormat').attr('checked')) {
                                all = v.ALLPREMIUM
                            } else {
                                all = v.ALLPREMIUM / 10000
                            }
                            var text
                            if (v.CHANNEL_COST) {
                                text = ' 1/' + (all/v.CHANNEL_COST).toFixed(2)
                            } else {
                                text = '--'
                            } */
                            if (unit === '万') {
                                all = v.ALLPREMIUM
                            } else {
                                all = v.ALLPREMIUM / 10000
                            }
                            // str += '<td>' + text
                            // str += ' </td></tr>'
                            str += '<td><span class="see_span" onclick="' + 'queryChannelCost(this)' + '">投产比</span><span class="hide">'
                            str += all
                            str += '</span><br\><span class="see_span" onClick="getDetails(this)">详情</span></td>'
                        }
                    })

                    var tableObj = $("#policyAmountTable");
                    tableObj.find("tbody").empty();
                    tableObj.find("tbody").append(str);

                    $('.policyAmountTable').find('tr:even').addClass('even')

                    if (!jsonData.depCode) {
                    	// 点击加载
                        $('.policyAmountTable .f2').click(function () {
                            var subJson = {}
                            $.extend(true, subJson, jsonData);
                            subJson.partnerCode = $(this).find('td:eq(1)').html().split('-')[0]
                            queryPartner(subJson, $(this).find('td:eq(0)').html())
                        })

                    }

                    // 点击单选按钮 阻止事件冒泡
                    /* $('.f2_radio').click(function (){
                        $('.f2').removeClass('selected')
                        $(this).parent().parent().addClass('selected')

                        // 兼容ie
                        if(event && event.stopPropagation) {
                        	//非IE
				          event.stopPropagation();
				        } else { //IE
				          window.event.cancelBubble = true;
				        }
                    }) */

                    // 分页导航栏
                    var strPage = creatNewChannelPage(page.current,4,page.maxPage,"1",page.size,page.total);
                    var pageDIV = $("#txproductpageDIV");
                    pageDIV[0].innerHTML="";
                    pageDIV.append(strPage);

                    // lfd added 20190911 -------start

                 // lfd added 20191023 -------start

                    // 配置提示信息内容
                    var str
                    if (jsonData.ispolicy && jsonData.ispremium){
                        str = "（下方表格中，每个合作伙伴对应两行，第一行为单量，单位为" + unit + "单；第二行为保费，单位为" + unit + "元。）";
                    } else if (jsonData.ispolicy) {
                        str = "（下方表格中，每个合作伙伴对应数字为单量，单位为" + unit + "单。）";
                    } else if (jsonData.ispremium) {
                        str = "（下方表格中，每个合作伙伴对应数字为保费，单位为" + unit + "元。）";
                    }

                    // 打开提示信息
                    $(".tips").html(str);
                    // 配置提示信息内容
                    //var str = "下方表格中，每个合作伙伴对应两行，第一行为单量，单位为单；第二行为保费，单位为元。";

                    //$(".tips").html(str);
                    // 打开提示信息
                    //$("#tip_box").css("display", "block");
                    // 打开提示信息 lfd added 20190911 -------end
                }
            })
        }

        /* 查询机构下的数据 */
        function queryPartner(jsonData, ind) {
            if (!jsonData || (!jsonData.ispolicy && !jsonData.ispremium))  {
                $.message("error", "请选择至少一项进行查询！");
                return false
            }

            // 清除数据
            /* if ($('.' + jsonData.partnerCode + '_tr').length > 0) {
                $('.' + jsonData.partnerCode + '_tr').remove()
                return false
            } */

            // 清除表格 lfd added
            delSubTable()


            $.openLoading();
            $.ajax({
                url : "dataManage/queryPartner",
                type : 'POST',
                async : true,
                dataType:'json',
                data: jsonData,
                success : function(data) {
                    $.closeLoading();

                    if (data.length === 0) {
                        $.message("error", "抱歉，该项没有数据！");
                        return false
                    }


                    // 整理数据
                    if (unit === '万') {
		                $.map(data, function (v, i) {
		                    for(prop in v) {
		                        if (prop != 'DEPT_ABR' && prop != 'DEPT_CODE' && prop != 'PARTNER_CODE'&& prop != 'CHANNEL_NAME') {
		                            v[prop] = formatNumber(v[prop], 2, '', 10000)
		                        }
		                    }
		                    return v
		                })
                    }

                    var str = '<table id="subtable" class="content_table_1 subtable"><thead>'

                    var thead_str = '<tr class="f1"><th style="width:2%; cursor: pointer;" onclick="delSubTable()"><img src="./images/retract.png" style="width:50%;" /></th><th style="width:3%;">序号</th><th style="width:6%;">机构</th>'
                           + getHead()
                           + '<th style="width:5%;">近12个月</th><th style="width:5%;">本年</th><th style="width:5%;">总量</th></tr>'
                   str += thead_str
                   str += '</thead><tbody>'

                   $.each(data, function (i, v){
                        //str += '<tr class="' + jsonData.partnerCode + '_tr"><td></td><td>' + ind + '.' + (i+1) + '</td><td></td><td>' + v.DEPT_CODE + '-' + v.DEPT_ABR + '<td>'
                        // str += '<tr class="next_tr ' + jsonData.partnerCode + '_tr"><td>' + ind + '.' + (i+1) + '</td><td></td><td>' + v.DEPT_CODE + '-' + v.DEPT_ABR + '<td>'
                        str += '<tr><td class="noborder"></td><td>' + ind + '.' + (i+1) + '</td><td>' + v.DEPT_CODE + '-' + v.DEPT_ABR + '<td>'
                        if (jsonData.ispolicy & jsonData.ispremium){
                            for (k = 11; k>=0; k--) {
                                str += '<div class="border_bottom">' + v['COUNT' + k] + '</div><div>' + v['PREMIUM' + k] + '</div></td><td>'
                            }
                            str += '<div class="border_bottom">' + v.POL_NUM + '</div><div>' + v.PREMIUM + '</div></td>'
                            // str += '<td><div class="border_bottom">' + v.ALLCOUNT + '</div><div>' + v.ALLPREMIUM + '</div></td>'
                            str += '<td><div class="border_bottom">' + v.ANNUAL_TOTAL_POL + '</div><div>' + v.ANNUAL_TOTAL_PREMIUM + '</div></td><td><div class="border_bottom">' + v.ALLCOUNT + '</div><div>' + v.ALLPREMIUM + '</div></td>'
                            str += '</tr>'
                        } else if (jsonData.ispolicy) {
                            for (k = 11; k>=0; k--) {
                                str += v['COUNT' + k] + '</div></td><td>'
                            }
                            str += v.POL_NUM + '</td><td>'
                            // str += v.ALLCOUNT + '</td></tr>'
                            str += v.ANNUAL_TOTAL_POL + '</td><td>'
                            str += v.ALLCOUNT + '</td></tr>'

                        } else if (jsonData.ispremium){
                            for (k = 11; k>=0; k--) {
                                str += v['PREMIUM' + k] + '</div></td><td>'
                            }
                            str += v.PREMIUM + '</td><td>'
                            str += v.ANNUAL_TOTAL_PREMIUM + '</td><td>'
                            str += v.ALLPREMIUM + '</td></tr>'
                            // str += v.ALLPREMIUM + '</td></tr>'
                        } else {
                            str = ''
                        }
                    })
                    str+="</tbody></table>"

                    // 序号 合作伙伴名称 设置rowspan
                    var pre_div = $('.policyAmountTable .f2:eq('+(ind-1)+')')

                    // lfd added 20191115 改变样式
                    pre_div.after('<tr><td class="subtable_box" colspan="17"></td></tr>')
                    $(".subtable_box").html(str)
                    // pre_div.after(str)
                }
            })
        }

        /* 点击详情 */
        function getDetails(ele) {

        	// 兼容ie
            if(event && event.stopPropagation) {
                //非IE
              event.stopPropagation();
            } else { //IE
              window.event.cancelBubble = true;
            }

            // 没有数据不查询详情和投产比 lfd added 20190911
            if ($(ele).prev().prev().html() === '0') {
                $.message("error", "抱歉，该合作伙伴没有数据！");
                return false
            }

        	$('.f2.selected').children().eq(1).text().split('-')[0]
        	var code = $(ele).parent().parent().children().eq(1).text().split('-')[0]||''
        	var name = $(ele).parent().parent().children().eq(1).text().split('-')[1]||''

            // window.location.href='dataManage/report/partner?partnerCode=' + $('.f2.selected').children().eq(1).text().split('-')[0];//此处拼接内容
            window.location.href='<%=path%>/dataManage/report/partner?partnerCode=' + code + '&partnerName=' + name;//此处拼接内容
        }
        /* 查询合作伙伴投入成本 */
        function queryChannelCost (obj) {
        	// 兼容ie
            if(event && event.stopPropagation) {
                //非IE
              event.stopPropagation();
            } else { //IE
              window.event.cancelBubble = true;
            }

        	// 没有数据不查询详情和投产比 lfd added 20190911
        	if ($(obj).next().html() === '0') {
                $.message("error", "抱歉，该合作伙伴没有数据！");
                return false
        	}

            var jsonData = {
            	channelCode: $(event.target).parent().parent().find('td:eq(1)').html().split('-')[0]
            }
            var _this = $(obj)
            $.openLoading();
            $.ajax({
                url : "dataManage/queryChannelCost",
                type : 'POST',
                async : true,
                dataType:'json',
                data: jsonData,
                success : function(data) {
                    $.closeLoading();

                    if (data.length > 0) {
                        var all = _this.next().html()
                        $.message("success", "投产比为1/" + (all/data[0].CHANNEL_COST).toFixed(2));
                    } else {
                    	$.message("error", "抱歉，没有查询到合作伙伴投入成本！");
                    }

                }
            })
        }
        // 导出Excel
        function downloadLifePolicyFile() {
        	var jsonData = {
                    "countDate": $('#currentTime').val()?$('#currentTime').val():(new Date()).Format('yyyy-MM-dd'),
                    "depCode": $('#dpt_name').val()?$('#dpt_name').val():"",
                    // 机构名称
                    "dptName": $('#dpt_name').val()?$("#dpt_name").find("option:selected").text():"",
                    "depAbr": $('#dpt_name').text()?$('#dpt_name').text().split('-')[1]:"",
                    // lfd added 20190910 修改为弹窗选择
                    // "partnerCode": $('#ptn_name').val()?$('#ptn_name').val():"",
                    "partnerCode": $('#ptn_code').val()?$('#ptn_code').val():"",
                    "policyType": $('#product_line').val()=="99"?"2":$('#product_line').val(),
                    "ispolicy": document.getElementById('ispolicy').checked,
                    "ispremium": document.getElementById('ispremium').checked,
                    "isLiability": $('#product_line').val()=="99"?true:false
                }
            var href='<%=path%>/dataManage/downloadPolicyFile?' + encodeSearchParams(jsonData)
            window.open(href, '_blank');
        }

        /**
         * 拼接对象为请求字符串
         * @param {Object} obj - 待拼接的对象
         * @returns {string} - 拼接成的请求字符串
         */
        function encodeSearchParams(obj) {
          var params = []

          Object.keys(obj).forEach(function (key) {
            var value = obj[key]
            // 如果值为undefined我们将其置空
            if (typeof value === 'undefined') {
              value = ''
            }
            // 对于需要编码的文本（比如说中文）我们要进行编码
            params.push([key, encodeURIComponent(value)].join('='))
          })

          return params.join("&")
        }
         // 弹窗重置按钮 lfd added 20190909
         function tempReset() {
        	 $('#partner_name').val('')
             $('#partner_code').val('')
         }
         // 弹窗查询合作伙伴名称 lfd added 20190909
         function setPartnerParam(displayPage, size) {
        	 if (!size) {
        		 size = 5
        	 }
             var jsonData = {
                 current: displayPage,
                 size: size,
                 partnerName: $('#partner_name').val(),
                 partnerCode: $('#partner_code').val()
             }
             queryPartnerInfo(jsonData)
         }
         function queryPartnerInfo(jsonData) {
             if (!jsonData) {
                 jsonData = {
                     current: 1,
                     size: 5
                 }
             }
             $.openLoading();
             $.ajax({
                 url : "dataManage/queryPartnerInfo",
                 type : 'POST',
                 async : true,
                 dataType:'json',
                 data: jsonData,
                 success : function(page) {
                     $.closeLoading();

                     if (!page || page.data.length === 0) {
                         $.message("error", "抱歉，该项没有数据！");
                     }

                     var radioObj ="<input class='input_fxk' name='radioPartner' type='radio'/>";
                     var fieldNames = "CHANNEL_NAME,PARTNER_CODE";
                     var tableContent = creatTable1(fieldNames,page,radioObj);
                     var tableObj = $("#templetTable");
                     tableObj.find("tbody").remove();
                     tableObj.append(tableContent);

                     var strPage = creatNewChannelPage(jsonData.current,4,page.maxPage,"2",page.size,page.total);
                     var pageDIV = $("#templetpageDIV");
                     pageDIV[0].innerHTML="";
                     pageDIV.append(strPage);

                     $("#searchPartnerDiv").OpenDiv();

                     bindradio();

                }
            })
         }
         // 取消按钮 关闭弹窗并重置输入框 lfd 20190910
         function closePartnerDiv() {
             tempReset();
             closeCurrentDIV("searchPartnerDiv");
         }
         /* 选择高亮   lfd 20190910*/
		function bindradio(){
		    $("input[name='radioPartner']").click(function(){
		        $("input[name='radioPartner']").parent().parent().removeClass("table_highlighter");
		        $(this).parent().parent().addClass("table_highlighter");
		    });
		}
        // 点击确定 写入数据
        function setPartner() {
            $("#ptn_name").val($(".table_highlighter td").eq(1).html())
            $("#ptn_code").val($(".table_highlighter td").eq(2).html())
            closePartnerDiv()
        }

        // 清楚下级机构表格
        function delSubTable() {
            $('.subtable_box').parent().remove()
        }

    </script>
</body>
